package utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CommUtils {

    /**
     * 文件转换为base64
     *
     * @param path
     * @return
     */
    public static String fileToBase64Str(String path) {
        // 对文件进行base64编码
        String base64 = "";
        try {
            File file = new File(path);
            byte[] content = new byte[(int) file.length()];
            FileInputStream inputStream = new FileInputStream(file);
            inputStream.read(content);
            inputStream.close();
            base64 = new String(Base64.encodeBase64(content));
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return base64;
    }


    /**
     * 获取验签
     *
     * @param data
     * @param secretKey
     * @return
     */
    public static String sign(Map<String, Object> data, String secretKey) {
        if (data == null || data.isEmpty()) {
            return null;
        }
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[0]);
        Arrays.sort(keyArray);
        StringBuilder buf = new StringBuilder();
        for (String k : keyArray) {
            if ("sign".equals(k)) {
                continue;
            }
            Object v = data.getOrDefault(k, "");
            buf.append(v);
        }
        buf.append(secretKey);
        //生成签名
        return MD5Utils.md5Hex(buf.toString(), "UTF-8")
                       .toUpperCase();
    }


}
